package com.org.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blockchain.API.TimeCoinAPI;
import com.org.common.PageBean;
import com.org.common.Result;
import com.org.pojo.CommunityActivity;
import com.org.pojo.NormalUser;
import com.org.pojo.Serve;
import com.org.pojo.ServeRespond;
import com.org.service.NormalUserService;
import com.org.service.ServeRespondService;
import com.org.service.ServeService;
import com.org.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import static com.blockchain.API.TimeCoinAPI.adminPK;

/**
 * ClassName: ServeRespondController
 * Package: com.org.controller
 * Description:
 *
 * @Author Origin
 * @Create 2024/2/15 18:30
 * @Version 1.0
 */

@RestController
@RequestMapping("/serveRespond")
@CrossOrigin//支持跨域
public class ServeRespondController {

    @Autowired
    private ServeRespondService serveRespondService;

    @Autowired
    private ServeService serveService;

    @Autowired
    private NormalUserService normalUserService;

    // 志愿者响应服务
    @PostMapping("/add")
    public Result add(@RequestBody Map<String, Object> params){
        Integer serveId = (Integer) params.get("serveId");
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userType = (Integer) map.get("userType");

        //普通用户可以响应
        if(userType != 1){
            return Result.error("非普通用户不允许选择服务！");
        }

        //发布状态可以响应
        Serve s = serveService.findById(serveId);
        if(!s.getState().equals("已发布")){
            return Result.error("服务不是'已发布'状态");
        }

        int serveRespondId;
        //人数限制
        if(s.getNumJoin() < s.getNumPeople()){
            serveRespondService.add(serveId);
            LambdaQueryWrapper<ServeRespond> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.orderByDesc(ServeRespond::getId);
            lambdaQueryWrapper.last("limit 1");
            serveRespondId = serveRespondService.getOne(lambdaQueryWrapper).getId();
        }else{
            return Result.error("当前服务选择人数已满！");
        }

        return Result.success(serveRespondId);
    }


    // 更新服务状态
    @PostMapping("/updateState")
    public Result updateState(@RequestBody Map<String, Object> params){
        Integer serveRespondId = (Integer) params.get("serveRespondId");
        String state = (String) params.get("state");
        serveRespondService.updateState(serveRespondId, state);
        return Result.success();
    }

   // 撤销选择服务
    @PostMapping("/revoke")
    public Result revoke(@RequestBody Map<String, Object> params){
        Integer serveRespondId = (Integer) params.get("serveRespondId");
        serveRespondService.revoke(serveRespondId);
        return Result.success("撤销完成！");
    }

    //  查看服务响应用户
    @GetMapping("/list")
    public Result<List<ServeRespond>> list(Integer id){ //服务id
        List<ServeRespond> l = serveRespondService.list(id);
        return Result.success(l);
    }

    //用户完成服务
    // 志愿者id、服务id以及转移数量
    @GetMapping("/complete")
    public Result complete(Integer userId, Integer serviceId, Integer num) throws Exception {
        // 根据志愿者id和服务id查询出服务响应id
        Integer id = serveRespondService.getOne(new LambdaQueryWrapper<ServeRespond>().eq(ServeRespond::getServeId, serviceId).eq(ServeRespond::getUserId, userId)).getId();
        CompletableFuture.runAsync(() -> {
            try {
                serveRespondService.complete(id, num);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).thenRun(() -> {  // 时间币交易完后
            // 服务响应
            ServeRespond serveRespond = serveRespondService.getById(id);
            // 志愿者
            NormalUser toUser = normalUserService.getById(serveRespond.getUserId());
            // 老人
            NormalUser fromUser = normalUserService.getById(serveService.getById(serveRespond.getServeId()).getCreateId());

            // 时间币交易完成，更新用户状态
            fromUser.setState("已通过实名认证");
            toUser.setState("已通过实名认证");
            normalUserService.updateById(fromUser);
            normalUserService.updateById(toUser);
            // 更新服务响应状态
            serveRespondService.updateState(id, "已完成");
        });

        return Result.success();
    }

    //删除绑定
    @GetMapping("/delete")
    public Result delete(Integer id){
        serveRespondService.delete(id);
        return Result.success();
    }

    @GetMapping("/allList")
    public Result<PageBean<ServeRespond>> list(
            Integer pageNum,
            Integer pageSize,   //每页几个
            @RequestParam String serve_id, //可以不携带
            @RequestParam String user_id,
            @RequestParam String state
    ){
        PageBean<ServeRespond> pb = serveRespondService.allList(pageNum, pageSize, serve_id, user_id, state);
        return Result.success(pb);
    }

    // 获取详细信息
    @GetMapping("/findById")
    public Result<ServeRespond> getCommunityActivityDetail(long id) {
        ServeRespond serveRespond = serveRespondService.getById(id);
        if (serveRespond.getState().equals("处理中")) {
            return Result.error("服务有关时间币正在处理中，请稍后再查看！");
        }
        return Result.success(serveRespondService.getById(id));
    }


    //@Scheduled(fixedRate = 59000)  // 每59秒执行一次
    @PostMapping("/refresh")
    public Result refresh(){
        serveRespondService.refresh();
        return Result.success();
    }

    // 查看自己报名了的服务的数量
    @GetMapping("/count")
    public Result count(){
        Map<String, Object> param = ThreadLocalUtil.get();
        Integer userId = (Integer) param.get("id");
        Long count = serveRespondService.count(new LambdaQueryWrapper<ServeRespond>().eq(ServeRespond::getUserId, userId));
        return Result.success(count);
    }
}
